package com.tadpole.music.presenter.wechat;

import com.tadpole.music.callback.BaseCallback;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.wechat.IwxView;
import com.tadpole.music.model.base.DataModel;
import com.tadpole.music.model.base.ModelToken;
import com.tadpole.music.presenter.base.BasePresenter;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 获取微信openId
 * Created By 孙岩
 * on 2020/12/3
 */
public class OpenIdPresenter extends BasePresenter<IwxView> {
    @SuppressWarnings("unchecked")
    public void getOpenId(String code){
        if(isViewAttached()){

            String url = UrlConfig.getWXOpenId + code + "&grant_type=authorization_code";
            DataModel.request(ModelToken.GET_REQUEST)
                    .url(url)
                    .execute(new BaseCallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            try{
                                JSONObject obj = new JSONObject(data);
                                String openID = obj.getString("openid");
                                String accessToken = obj.getString("access_token");
                                getView().showOpenId(openID,accessToken);
                            }catch (JSONException e){
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            getView().showError();
                        }

                        @Override
                        public void onBefore() {

                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        }
    }
}
